package com.megvii.koala.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.megvii.koala.constance.ErrorCode;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

/**
 * Created by linyue on 16/3/3.
 */
public class WeChatUtil
{
    private static Context context;

    private static IWXAPI api;

    public static final IWXAPI init(final Context context, String appId)
    {
        if (api == null)
        {
            WeChatUtil.context = context;
            WeChatUtil.api = WXAPIFactory.createWXAPI(context, appId, false);
            WeChatUtil.api.registerApp(appId);
        }
        return api;
    }

    /**
     * 微信分享链接
     *
     * @param title
     * @param description
     * @param iconResId
     * @param flag        {@link com.tencent.mm.sdk.modelmsg.SendMessageToWX.Req}中的WXSceneSession(好友，群),WXSceneTimeline(朋友圈),WXSceneFavorite(收藏)
     * @return
     */
    public static int shareLink(String url, String title, String description, int iconResId,
            int flag)
    {
        int errorCode = verifySDK();
        if (errorCode != ErrorCode.NO_ERROR)
        {
            return errorCode;
        }
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = url;
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = title;
        msg.description = description;
        Bitmap thumb = BitmapFactory.decodeResource(context.getResources(), iconResId);
        msg.setThumbImage(thumb);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;
        req.scene = flag;
        api.sendReq(req);
        api.isWXAppSupportAPI();
        return ErrorCode.NO_ERROR;
    }

    private static int verifySDK()
    {
        if (!api.isWXAppInstalled())
        {
            return ErrorCode.WE_CHAT_NOT_INSTALLED;
        }
        if (!api.isWXAppSupportAPI())
        {
            return ErrorCode.ANDROID_API_NOT_SUPPORT_WE_CHAT_SDK;
        }
        return ErrorCode.NO_ERROR;
    }
}
